﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace Enter.DataCommon
{
	public static class ObjectExtension
	{
		/// <summary>
		/// 根据类型 名称 获取context值
		/// </summary>
		/// <param name="ty">类型</param>
		/// <param name="name">名称</param>
		/// <returns></returns>
		public static object GetValueByType(Type ty, object value)
		{
			if (value != null)
			{
				try
				{
					object result = new object();
					string Objvalue = string.Empty;
					Objvalue = string.Format("\"{0}\"", value);
					result = JsonConvert.DeserializeObject(Objvalue, ty);
					return result;
				}
				catch
				{
					return null;
				}
			}

			return null;
		}

        #region To T

        /// <summary>
        /// 将字符转换成自己的类型
        /// </summary>
        /// <param name="val">System.String</param>
        /// <returns>如果转换失败将返回 T 的默认值</returns>
        public static T To<T>(this object val)
        {
            if (val != null)
            {
                return val.To<T>(default(T));
            }
            else
            {
                return default(T);
            }
        }
        /// <summary>
        /// 将字符转换成自己的类型
        /// </summary>
        /// <param name="val">System.Object</param>
        /// <param name="defVal">在转换成 T 失败时，返回的默认值</param>
        /// <returns>类型 T 的值</returns>
        public static T To<T>(this object val, T defVal)
        {
            if (val == null)
                return (T)defVal;
            if (val is T)
                return (T)val;

            Type type = typeof(T);
            try
            {
                if (type.BaseType == typeof(Enum))
                {
                    return (T)Enum.Parse(type, val.ToString(), true);
                }
                else
                {
                    return (T)Convert.ChangeType(val, type);
                }
            }
            catch
            {
                return defVal;
            }
        }

        #endregion
	}
}
